package org.tmsps.ne4spring.utils.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.tmsps.ne4spring.utils.ChkUtil;
import org.tmsps.ne4spring.utils.JsonUtil;

public class HttpPostFileTools {

	public synchronized static boolean downLoad(String url, Map<String, String> paramMap, String localPath) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		OutputStream out = null;
		InputStream in = null;

		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
			if (ChkUtil.isNotNull(paramMap)) {
				StringEntity se = new StringEntity(JsonUtil.toJson(paramMap), "UTF-8");
				httpPost.setEntity(se);
			}

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity entity = httpResponse.getEntity();
			in = entity.getContent();

			long length = entity.getContentLength();
			if (length <= 0) {
				System.out.println("下载文件不存在！");
				return false;
			}
			System.err.println("length:" + length);

			File file = new File(localPath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}

			out = new FileOutputStream(file);
			byte[] buffer = new byte[10240];
			int readLength = 0;

			while ((readLength = in.read(buffer)) > 0) {
				out.write(buffer, 0, readLength);
			}

			out.flush();

		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}

}
